#include "block_queue.hpp"
#include "task.hpp"
#include <ctime>
#include <cstdlib>

//using namespace std;
using namespace ns_block_queue;
using namespace ns_task;
//class ns_task::Task;

pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;

void* product(void* args)
{
    BlockQueue<Task>* bq = (BlockQueue<Task>*)args;
    while(true)
    {
        //sleep(1);
        std::string s = "+-*/%";
        int left = rand() % 50 + 1;
        int right =  rand() % 10 + 1;
        char op = s[rand()%5];
        Task t(left, right, op);
        bq->push(t);
	pthread_mutex_lock(&mtx);
        std::cout << "生产者生产的数据是 " << left << " " << op << " " << right << " = ??" << std::endl;
        pthread_mutex_unlock(&mtx);
    }
}

void* consume(void* args)
{ 
    BlockQueue<Task>* bq = (BlockQueue<Task>*)args;
    while(true)
    {
        sleep(1);
        //int data = 0;
        Task data;
        bq->pop(&data);
	
        pthread_mutex_lock(&mtx);
        std::cout << "我是[" << pthread_self() << "] 消费者消费的数据是 " << data.d1 << " " << data.op << " " << data.d2 << " = " << data.run() << std::endl;
        pthread_mutex_unlock(&mtx);
    }
}

int main()
{
    pthread_t c, p;
    pthread_t c1, c2, c3;
    srand(time(nullptr));
    BlockQueue<Task>* bq = new BlockQueue<Task>();
    pthread_create(&p, nullptr, product, (void*)bq);
    pthread_create(&c, nullptr, consume, (void*)bq);
    pthread_create(&c1, nullptr, consume, (void*)bq);
    pthread_create(&c2, nullptr, consume, (void*)bq);
    pthread_create(&c3, nullptr, consume, (void*)bq);

    pthread_join(p, nullptr);
    pthread_join(c, nullptr);
    pthread_join(c1, nullptr);
    pthread_join(c2, nullptr);
    pthread_join(c3, nullptr);
    delete bq;

    return 0;
}
